import XLSX from "xlsx";
import fs from "fs";

// 示例数据
const data  = [];
/**
 * 返回是否为汉字（基础范围）
 */
function isHan(ch) {
  if (!ch) return false;
  const code = ch.charCodeAt(0);
  return (code >= 0x4e00 && code <= 0x9fff) || (code >= 0x3400 && code <= 0x4dbf);
}

/**
 * 若 s 为若干次重复同一子串的连接（例如 "盟书盟书"），则返回最小重复单元；否则返回 s 自身。
 */
function reduceRepeated(s) {
  const n = s.length;
  for (let k = 1; k <= Math.floor(n / 2); k++) {
    if (n % k !== 0) continue;
    const unit = s.slice(0, k);
    if (unit.repeat(n / k) === s) return unit;
  }
  return s;
}

/**
 * 解析 head，返回 { english, chinese, pinyin }
 */
function parseHead(head) {
  if (!head || typeof head !== "string") return { english: "", chinese: "", pinyin: "" };

  const text = head.replace(/\t+/g, " ").replace(/\s+/g, " ").trim();

  let firstHan = -1;
  let lastHan = -1;
  for (let i = 0; i < text.length; i++) if (isHan(text[i])) { firstHan = i; break; }
  for (let i = text.length - 1; i >= 0; i--) if (isHan(text[i])) { lastHan = i; break; }

  if (firstHan === -1) return { english: text, chinese: "", pinyin: "" };

  // 处理括号内英文的情况
  const openParenIdx = text.lastIndexOf("(", firstHan);
  const closeParenIdx = text.indexOf(")", firstHan);
  if (openParenIdx !== -1 && closeParenIdx !== -1 && openParenIdx < firstHan && closeParenIdx >= firstHan) {
    let nextHanAfterClose = -1;
    for (let i = closeParenIdx + 1; i < text.length; i++) {
      if (isHan(text[i])) { nextHanAfterClose = i; break; }
    }
    if (nextHanAfterClose !== -1) {
      firstHan = nextHanAfterClose;
      if (lastHan <= closeParenIdx) {
        for (let i = text.length - 1; i > closeParenIdx; i--) {
          if (isHan(text[i])) { lastHan = i; break; }
        }
      }
    }
  }

  let englishEnd = firstHan;
  const openParenBefore = text.lastIndexOf("(", firstHan);
  const closeParenAfter = text.indexOf(")", firstHan);
  if (openParenBefore !== -1 && closeParenAfter !== -1 && openParenBefore < firstHan && closeParenAfter >= firstHan) {
    englishEnd = closeParenAfter + 1;
  } else {
    englishEnd = firstHan;
  }

  const englishPart = text.slice(0, englishEnd).trim();

  let chineseStart = firstHan;
  let chineseEnd = lastHan;

  while (chineseStart - 1 >= 0) {
    const ch = text[chineseStart - 1];
    if (ch === ")") break;
    if (isHan(ch) || /[-–—··•·]/.test(ch)) chineseStart--;
    else break;
  }
  while (chineseEnd + 1 < text.length) {
    const ch = text[chineseEnd + 1];
    if (ch === ")") break;
    if (isHan(ch) || /[-–—··•·]/.test(ch)) chineseEnd++;
    else break;
  }

  let chineseRaw = text.slice(chineseStart, chineseEnd + 1).trim();
  chineseRaw = reduceRepeated(chineseRaw);

  const afterChinese = text.slice(chineseEnd + 1).trim();

  // ===== 改写拼音匹配 =====
  // 使用 Unicode 字母匹配，兼容拼音特殊字符（如 ɡ）
  const pinyinRegex = /[\p{L}\d·ˉˊˇˋü: ]+/gu;
  const pinyinMatch = afterChinese.match(pinyinRegex);
  const pinyin = pinyinMatch ? pinyinMatch.join("").trim() : "";

  let english = englishPart;
  if (!english) {
    const left = text.slice(0, chineseStart).trim();
    english = left;
  }
  english = english.replace(/\s+$/g, "").replace(/\s*\(\s*\)/g, "").trim();

  return { english, chinese: chineseRaw, pinyin };
}

// 将数据构造成 Excel 可写结构
const excelData = data.map((item) => {
  const { english, chinese, pinyin } = parseHead(item.head);
  return {
    英文名称: english,
    中文名称: chinese,
    拼音: pinyin,
    释文: item.content || "",
  };
});

// 可选：若单元格内容过长（> 32000），这里自动分段到多列，避免 xlsx 报错
function splitLongTextFields(rows, fieldName, chunkSize = 30000) {
  return rows.map((row) => {
    const text = row[fieldName] || "";
    if (text.length <= chunkSize) return row;
    const chunks = [];
    for (let i = 0; i < text.length; i += chunkSize) {
      chunks.push(text.slice(i, i + chunkSize));
    }
    const newRow = { ...row };
    // 删除原字段并改为内容1/内容2...
    delete newRow[fieldName];
    chunks.forEach((ch, idx) => {
      newRow[`${fieldName}_${idx + 1}`] = ch;
    });
    return newRow;
  });
}

// 如果担心内容过长，可以取消注释下面一行以自动分割"内容"列
const safeExcelData = splitLongTextFields(excelData, "释文", 30000);

// 写入 Excel
const worksheet = XLSX.utils.json_to_sheet(safeExcelData);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
const filePath = "./辞海英文版书稿文稿.xlsx";
XLSX.writeFile(workbook, filePath);

console.log(`✅ 已生成 Excel 文件：${filePath}`);